#include "reportswidget.h"
#include <QDateTime>
#include <QFileDialog>
#include <QTextStream>
#include <QApplication>
#include <QDebug>
#include <QLocale>

ReportsWidget::ReportsWidget(QWidget *parent)
    : QWidget(parent), m_refreshTimer(new QTimer(this)), m_isUpdating(false)
{
    initializeUI();

    // 设置自动刷新（每2分钟）
    m_refreshTimer->setSingleShot(false);
    m_refreshTimer->setInterval(120000);
    connect(m_refreshTimer, &QTimer::timeout, this, &ReportsWidget::onAutoRefresh);
    m_refreshTimer->start();

    // 初始化加载数据
    refreshReports();
}

ReportsWidget::~ReportsWidget()
{
}

// 初始化界面
void ReportsWidget::initializeUI()
{
    m_mainLayout = new QVBoxLayout(this);

    // 创建工具栏
    QHBoxLayout *toolbarLayout = new QHBoxLayout;

    toolbarLayout->addWidget(new QLabel("时间范围:"));
    m_timeRangeCombo = new QComboBox;
    m_timeRangeCombo->addItems({"本月", "最近3个月", "最近6个月", "最近一年", "自定义"});
    m_timeRangeCombo->setCurrentText("本月");
    toolbarLayout->addWidget(m_timeRangeCombo);

    toolbarLayout->addWidget(new QLabel("开始日期:"));
    m_startDateEdit = new QDateEdit;
    m_startDateEdit->setDate(QDate::currentDate().addMonths(-1));
    m_startDateEdit->setEnabled(false);
    toolbarLayout->addWidget(m_startDateEdit);

    toolbarLayout->addWidget(new QLabel("结束日期:"));
    m_endDateEdit = new QDateEdit;
    m_endDateEdit->setDate(QDate::currentDate());
    m_endDateEdit->setEnabled(false);
    toolbarLayout->addWidget(m_endDateEdit);

    m_refreshBtn = new QPushButton("刷新");
    m_exportBtn = new QPushButton("导出");
    toolbarLayout->addWidget(m_refreshBtn);
    toolbarLayout->addWidget(m_exportBtn);
    toolbarLayout->addStretch();

    m_mainLayout->addLayout(toolbarLayout);

    // 创建滚动区域
    m_scrollArea = new QScrollArea;
    m_scrollContent = new QWidget;
    m_scrollArea->setWidget(m_scrollContent);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setMinimumWidth(600);
    m_scrollContent->setMinimumWidth(580);

    QVBoxLayout *contentLayout = new QVBoxLayout(m_scrollContent);

    // 添加各个统计面板
    contentLayout->addWidget(createOverviewPanel());
    contentLayout->addWidget(createInventoryPanel());
    contentLayout->addWidget(createOperationPanel());
    contentLayout->addWidget(createTrendPanel());
    contentLayout->addStretch();

    m_mainLayout->addWidget(m_scrollArea);

    // 连接信号槽
    connect(m_timeRangeCombo, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
            this, &ReportsWidget::onDateRangeChanged);
    connect(m_startDateEdit, &QDateEdit::dateChanged, this, &ReportsWidget::refreshReports);
    connect(m_endDateEdit, &QDateEdit::dateChanged, this, &ReportsWidget::refreshReports);
    connect(m_refreshBtn, &QPushButton::clicked, this, &ReportsWidget::refreshReports);
    connect(m_exportBtn, &QPushButton::clicked, this, &ReportsWidget::exportReports);
}

// 创建概览统计面板
QWidget *ReportsWidget::createOverviewPanel()
{
    QGroupBox *overviewGroup = new QGroupBox("系统概览");
    QGridLayout *layout = new QGridLayout(overviewGroup);

    // 创建统计卡片
    QFrame *totalItemsCard = createStatCard("物品总数", "0", "种类");
    QFrame *totalQuantityCard = createStatCard("库存总量", "0", "件");
    QFrame *monthlyOpsCard = createStatCard("本月操作", "0", "次");
    QFrame *avgQuantityCard = createStatCard("平均库存", "0.0", "件/种");

    layout->addWidget(totalItemsCard, 0, 0);
    layout->addWidget(totalQuantityCard, 0, 1);
    layout->addWidget(monthlyOpsCard, 1, 0);
    layout->addWidget(avgQuantityCard, 1, 1);

    // 设置更好的间距和拉伸
    layout->setHorizontalSpacing(15);
    layout->setVerticalSpacing(15);
    layout->setContentsMargins(15, 15, 15, 15);
    layout->setColumnStretch(0, 1);
    layout->setColumnStretch(1, 1);
    layout->setRowStretch(0, 1);
    layout->setRowStretch(1, 1);

    // 保存标签引用用于更新数据
    m_totalItemsLabel = totalItemsCard->findChild<QLabel *>("valueLabel");
    m_totalQuantityLabel = totalQuantityCard->findChild<QLabel *>("valueLabel");
    m_monthlyOpsLabel = monthlyOpsCard->findChild<QLabel *>("valueLabel");
    m_avgQuantityLabel = avgQuantityCard->findChild<QLabel *>("valueLabel");

    return overviewGroup;
}

// 创建库存统计面板
QWidget *ReportsWidget::createInventoryPanel()
{
    QGroupBox *inventoryGroup = new QGroupBox("库存统计");
    QVBoxLayout *layout = new QVBoxLayout(inventoryGroup);

    // 库存排行榜 - 使用圆形卡片
    QGroupBox *topItemsGroup = new QGroupBox("库存排行榜");
    QHBoxLayout *topItemsLayout = new QHBoxLayout(topItemsGroup);
    topItemsLayout->setSpacing(15);
    topItemsLayout->setContentsMargins(15, 15, 15, 15);
    
    // 创建5个圆形卡片容器
    m_topItemsContainer = new QWidget();
    QHBoxLayout *containerLayout = new QHBoxLayout(m_topItemsContainer);
    containerLayout->setSpacing(15);
    
    // 初始创建空的圆形卡片
    for (int i = 0; i < 5; i++) {
        QFrame *circleCard = createCircleCard(QString("第%1名").arg(i+1), "暂无", "0件");
        containerLayout->addWidget(circleCard);
    }
    containerLayout->addStretch();
    
    topItemsLayout->addWidget(m_topItemsContainer);
    layout->addWidget(topItemsGroup);

    return inventoryGroup;
}

// 创建操作统计面板
QWidget *ReportsWidget::createOperationPanel()
{
    QGroupBox *operationGroup = new QGroupBox("操作统计");
    QVBoxLayout *layout = new QVBoxLayout(operationGroup);

    QHBoxLayout *statsLayout = new QHBoxLayout;
    statsLayout->setSpacing(15);
    statsLayout->setContentsMargins(10, 10, 10, 10);

    QFrame *stockInCard = createStatCard("入库次数", "0", "次");
    QFrame *stockOutCard = createStatCard("出库次数", "0", "次");
    statsLayout->addWidget(stockInCard);
    statsLayout->addWidget(stockOutCard);
    statsLayout->addStretch();

    m_stockInCountLabel = stockInCard->findChild<QLabel *>("valueLabel");
    m_stockOutCountLabel = stockOutCard->findChild<QLabel *>("valueLabel");

    layout->addLayout(statsLayout);

    // 用户活跃度排行榜 - 使用圆形卡片
    QGroupBox *userActivityGroup = new QGroupBox("用户活跃度排行榜");
    QHBoxLayout *userActivityLayout = new QHBoxLayout(userActivityGroup);
    userActivityLayout->setSpacing(15);
    userActivityLayout->setContentsMargins(15, 15, 15, 15);
    
    // 创建5个圆形卡片容器
    m_userActivityContainer = new QWidget();
    QHBoxLayout *userContainerLayout = new QHBoxLayout(m_userActivityContainer);
    userContainerLayout->setSpacing(15);
    
    // 初始创建空的圆形卡片
    for (int i = 0; i < 5; i++) {
        QFrame *circleCard = createCircleCard(QString("第%1名").arg(i+1), "暂无", "0次");
        userContainerLayout->addWidget(circleCard);
    }
    userContainerLayout->addStretch();
    
    userActivityLayout->addWidget(m_userActivityContainer);
    layout->addWidget(userActivityGroup);

    return operationGroup;
}

// 创建趋势分析面板
QWidget *ReportsWidget::createTrendPanel()
{
    QGroupBox *trendGroup = new QGroupBox("趋势分析");
    QHBoxLayout *layout = new QHBoxLayout(trendGroup);

    m_stockInChart = new SimpleChartWidget("月度入库趋势");
    m_stockOutChart = new SimpleChartWidget("月度出库趋势");

    layout->addWidget(m_stockInChart);
    layout->addWidget(m_stockOutChart);

    return trendGroup;
}

// 创建统计卡片
QFrame *ReportsWidget::createStatCard(const QString &title, const QString &value, const QString &subText)
{
    QFrame *card = new QFrame;
    card->setFrameStyle(QFrame::NoFrame); // 移除边框避免遮挡
    card->setStyleSheet(
        "QFrame { "
        "    background: white; "
        "    border: 2px solid #e0e0e0; "
        "    border-radius: 12px; "
        "    padding: 0px; "
        "}"
    );
    card->setMinimumSize(180, 130);
    card->setMaximumHeight(150);

    QVBoxLayout *layout = new QVBoxLayout(card);
    layout->setSpacing(5);
    layout->setContentsMargins(20, 15, 20, 15);

    // 标题标签
    QLabel *titleLabel = new QLabel(title);
    titleLabel->setStyleSheet(
        "font-size: 13px; "
        "color: #666; "
        "font-weight: bold; "
        "background: transparent; "
        "border: none;"
    );
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setWordWrap(true);
    layout->addWidget(titleLabel);

    // 添加弹性空间
    layout->addSpacing(5);

    // 数值标签 - 确保充足空间
    QLabel *valueLabel = new QLabel(value);
    valueLabel->setObjectName("valueLabel");
    valueLabel->setStyleSheet(
        "font-size: 32px; "
        "color: #2196F3; "
        "font-weight: bold; "
        "background: transparent; "
        "border: none; "
        "padding: 5px;"
    );
    valueLabel->setAlignment(Qt::AlignCenter);
    valueLabel->setWordWrap(true);
    valueLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    valueLabel->setMinimumHeight(50);
    layout->addWidget(valueLabel);

    // 添加弹性空间
    layout->addSpacing(5);

    // 单位标签
    if (!subText.isEmpty())
    {
        QLabel *subLabel = new QLabel(subText);
        subLabel->setStyleSheet(
            "font-size: 12px; "
            "color: #999; "
            "background: transparent; "
            "border: none;"
        );
        subLabel->setAlignment(Qt::AlignCenter);
        subLabel->setWordWrap(true);
        layout->addWidget(subLabel);
    }

    return card;
}

// 创建圆形卡片
QFrame *ReportsWidget::createCircleCard(const QString &rank, const QString &name, const QString &value)
{
    QFrame *card = new QFrame;
    card->setFixedSize(100, 120);
    card->setStyleSheet("QFrame { background: transparent; border: none; }");

    QVBoxLayout *layout = new QVBoxLayout(card);
    layout->setSpacing(8);
    layout->setContentsMargins(5, 5, 5, 5);

    // 创建圆形容器
    QFrame *circle = new QFrame;
    circle->setFixedSize(80, 80);
    circle->setStyleSheet(
        "QFrame {"
        "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
        "        stop:0 #4CAF50, stop:1 #45a049);"
        "    border-radius: 40px;"
        "    border: 3px solid white;"
        "}"
    );

    // 圆形内的布局
    QVBoxLayout *circleLayout = new QVBoxLayout(circle);
    circleLayout->setSpacing(2);
    circleLayout->setContentsMargins(8, 8, 8, 8);

    // 排名标签
    QLabel *rankLabel = new QLabel(rank);
    rankLabel->setStyleSheet("font-size: 10px; color: white; font-weight: bold;");
    rankLabel->setAlignment(Qt::AlignCenter);
    circleLayout->addWidget(rankLabel);

    // 数值标签
    QLabel *valueLabel = new QLabel(value);
    valueLabel->setObjectName("circleValue");
    valueLabel->setStyleSheet("font-size: 16px; color: white; font-weight: bold;");
    valueLabel->setAlignment(Qt::AlignCenter);
    valueLabel->setWordWrap(true);
    circleLayout->addWidget(valueLabel);

    // 名称标签（在圆形外面）
    QLabel *nameLabel = new QLabel(name);
    nameLabel->setObjectName("circleName");
    nameLabel->setStyleSheet("font-size: 12px; color: #333; font-weight: bold;");
    nameLabel->setAlignment(Qt::AlignCenter);
    nameLabel->setWordWrap(true);
    nameLabel->setMaximumWidth(100);

    // 添加到主布局
    layout->addWidget(circle, 0, Qt::AlignCenter);
    layout->addWidget(nameLabel);
    layout->addStretch();

    return card;
}

// 数值格式化函数 - 优化大数字显示
QString ReportsWidget::formatNumber(int number)
{
    if (number >= 10000000) {
        // 1000万以上显示为百万单位
        return QString("%1M").arg(QString::number(number / 1000000.0, 'f', 1));
    } else if (number >= 100000) {
        // 10万以上显示为万单位
        return QString("%1万").arg(QString::number(number / 10000.0, 'f', 1));
    } else if (number >= 10000) {
        // 1万以上显示为万单位
        return QString("%1万").arg(QString::number(number / 10000.0, 'f', 1));
    } else {
        // 1万以下直接显示
        return QString::number(number);
    }
}

QString ReportsWidget::formatDecimal(double number, int precision)
{
    return QString::number(number, 'f', precision);
}

// 刷新所有报表数据
void ReportsWidget::refreshReports()
{
    // 防止并发更新
    if (m_isUpdating)
    {
        return;
    }

    m_isUpdating = true;

    try
    {
        updateOverviewData();
        updateInventoryData();
        updateOperationData();
        updateTrendData();
    }
    catch (...)
    {
        qDebug() << "Error occurred during reports refresh";
    }

    m_isUpdating = false;
}

// 更新概览数据
void ReportsWidget::updateOverviewData()
{
    try
    {
        DatabaseManager &db = DatabaseManager::getInstance();
        QVariantMap summary = db.getDashboardSummary();

        if (m_totalItemsLabel)
        {
            m_totalItemsLabel->setText(formatNumber(summary.value("totalItems", 0).toInt()));
        }
        if (m_totalQuantityLabel)
        {
            m_totalQuantityLabel->setText(formatNumber(summary.value("totalQuantity", 0).toInt()));
        }
        if (m_monthlyOpsLabel)
        {
            m_monthlyOpsLabel->setText(formatNumber(summary.value("monthlyOperations", 0).toInt()));
        }

        // 获取并更新库存统计数据
        InventoryStatistics stats = db.getDetailedInventoryStatistics();
        if (m_avgQuantityLabel)
        {
            m_avgQuantityLabel->setText(formatDecimal(stats.averageQuantity, 1));
        }
    }
    catch (...)
    {
        qDebug() << "Error in updateOverviewData";
    }
}

// 更新库存统计数据
void ReportsWidget::updateInventoryData()
{
    try
    {
        DatabaseManager &db = DatabaseManager::getInstance();
        InventoryStatistics stats = db.getDetailedInventoryStatistics();

        // 更新圆形卡片显示
        if (m_topItemsContainer)
        {
            QHBoxLayout* layout = qobject_cast<QHBoxLayout*>(m_topItemsContainer->layout());
            if (layout)
            {
                // 清除旧的卡片（除了最后的stretch）
                while (layout->count() > 1) {
                    QLayoutItem* item = layout->takeAt(0);
                    if (item->widget()) {
                        item->widget()->deleteLater();
                    }
                    delete item;
                }
                
                // 创建新的圆形卡片
                for (int i = 0; i < 5; i++)
                {
                    QString rank = QString("第%1名").arg(i + 1);
                    QString name = "暂无";
                    QString value = "0件";
                    
                    if (i < stats.topItems.size())
                    {
                        name = stats.topItems[i].first;
                        value = QString("%1件").arg(stats.topItems[i].second);
                        
                        // 限制名称长度
                        if (name.length() > 6) {
                            name = name.left(5) + "...";
                        }
                    }
                    
                    QFrame* circleCard = createCircleCard(rank, name, value);
                    layout->insertWidget(i, circleCard);
                }
            }
        }
    }
    catch (...)
    {
        qDebug() << "Error in updateInventoryData";
    }
}

// 更新操作统计数据
void ReportsWidget::updateOperationData()
{
    try
    {
        DatabaseManager &db = DatabaseManager::getInstance();
        QString startDate, endDate;

        // 根据时间范围获取统计数据
        if (m_timeRangeCombo && m_timeRangeCombo->currentText() == "自定义")
        {
            if (m_startDateEdit && m_endDateEdit)
            {
                startDate = m_startDateEdit->date().toString("yyyy-MM-dd");
                endDate = m_endDateEdit->date().toString("yyyy-MM-dd");
            }
        }

        OperationStatistics stats = db.getDetailedOperationStatistics(startDate, endDate);

        if (m_stockInCountLabel)
        {
            m_stockInCountLabel->setText(formatNumber(stats.stockInCount));
        }
        if (m_stockOutCountLabel)
        {
            // 添加调试信息
            qDebug() << "出库次数原始数据:" << stats.stockOutCount;
            m_stockOutCountLabel->setText(formatNumber(stats.stockOutCount));
        }

        // 更新用户活跃度圆形卡片显示
        if (m_userActivityContainer)
        {
            QHBoxLayout* layout = qobject_cast<QHBoxLayout*>(m_userActivityContainer->layout());
            if (layout)
            {
                // 清除旧的卡片（除了最后的stretch）
                while (layout->count() > 1) {
                    QLayoutItem* item = layout->takeAt(0);
                    if (item->widget()) {
                        item->widget()->deleteLater();
                    }
                    delete item;
                }
                
                // 创建新的圆形卡片
                for (int i = 0; i < 5; i++)
                {
                    QString rank = QString("第%1名").arg(i + 1);
                    QString name = "暂无";
                    QString value = "0次";
                    
                    if (i < stats.userActivity.size())
                    {
                        name = stats.userActivity[i].first;
                        value = QString("%1次").arg(stats.userActivity[i].second);
                        
                        // 限制用户名长度
                        if (name.length() > 6) {
                            name = name.left(5) + "...";
                        }
                    }
                    
                    // 为用户活跃度使用不同颜色的圆形卡片
                    QFrame* circleCard = createCircleCard(rank, name, value);
                    // 修改用户活跃度卡片的颜色
                    QFrame* circle = circleCard->findChild<QFrame*>();
                    if (circle) {
                        circle->setStyleSheet(
                            "QFrame {"
                            "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                            "        stop:0 #2196F3, stop:1 #1976D2);"
                            "    border-radius: 40px;"
                            "    border: 3px solid white;"
                            "}"
                        );
                    }
                    
                    layout->insertWidget(i, circleCard);
                }
            }
        }
    }
    catch (...)
    {
        qDebug() << "Error in updateOperationData";
    }
}

// 更新趋势数据
void ReportsWidget::updateTrendData()
{
    try
    {
        DatabaseManager &db = DatabaseManager::getInstance();

        int months = 6; // 默认显示6个月数据
        if (m_timeRangeCombo && m_timeRangeCombo->currentText() == "最近一年")
        {
            months = 12;
        }

        TrendData trendData = db.getTrendAnalysisData(months);

        if (m_stockInChart)
        {
            m_stockInChart->setChartData(trendData.monthlyStockIn);
        }
        if (m_stockOutChart)
        {
            m_stockOutChart->setChartData(trendData.monthlyStockOut);
        }
    }
    catch (...)
    {
        qDebug() << "Error in updateTrendData";
    }
}

// 时间范围改变时刷新统计数据
void ReportsWidget::onDateRangeChanged()
{
    bool isCustom = (m_timeRangeCombo->currentText() == "自定义");
    m_startDateEdit->setEnabled(isCustom);
    m_endDateEdit->setEnabled(isCustom);

    if (!isCustom)
    {
        QDate endDate = QDate::currentDate();
        QDate startDate;

        if (m_timeRangeCombo->currentText() == "本月")
        {
            startDate = QDate(endDate.year(), endDate.month(), 1);
        }
        else if (m_timeRangeCombo->currentText() == "最近3个月")
        {
            startDate = endDate.addMonths(-3);
        }
        else if (m_timeRangeCombo->currentText() == "最近6个月")
        {
            startDate = endDate.addMonths(-6);
        }
        else if (m_timeRangeCombo->currentText() == "最近一年")
        {
            startDate = endDate.addYears(-1);
        }

        m_startDateEdit->setDate(startDate);
        m_endDateEdit->setDate(endDate);
    }

    refreshReports();
}

// 自动刷新定时器
void ReportsWidget::onAutoRefresh()
{
    refreshReports();
}

// 导出统计报表
void ReportsWidget::exportReports()
{
    QString fileName = QFileDialog::getSaveFileName(this, "导出统计报表",
                                                    QString("统计报表_%1.csv").arg(QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss")),
                                                    "CSV Files (*.csv)");
    if (fileName.isEmpty())
    {
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::warning(this, "导出失败", "无法创建文件: " + file.errorString());
        return;
    }

    QTextStream out(&file);
    out.setCodec("GBK");

    // 导出概览统计
    out << QString("仓库管理系统统计报表\n");
    out << QString("生成时间,") << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << QString("\n\n");

    out << QString("系统概览\n");
    out << QString("指标,数值\n");
    out << QString("物品总数,") << (m_totalItemsLabel ? m_totalItemsLabel->text() : "0") << QString("\n");
    out << QString("库存总量,") << (m_totalQuantityLabel ? m_totalQuantityLabel->text() : "0") << QString("\n");
    out << QString("本月操作,") << (m_monthlyOpsLabel ? m_monthlyOpsLabel->text() : "0") << QString("\n");
    out << QString("平均库存,") << (m_avgQuantityLabel ? m_avgQuantityLabel->text() : "0") << QString("\n\n");

    out << QString("操作统计\n");
    out << QString("入库次数,") << (m_stockInCountLabel ? m_stockInCountLabel->text() : "0") << QString("\n");
    out << QString("出库次数,") << (m_stockOutCountLabel ? m_stockOutCountLabel->text() : "0") << QString("\n\n");

    file.close();

    QMessageBox::information(this, "导出成功", QString("统计报表已导出到: %1").arg(fileName));
}

void ReportsWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);

    // 确保滚动区域在窗口尺寸变化时正确调整
    if (m_scrollArea && event->size().isValid())
    {
        // 暂时停止刷新定时器，避免在尺寸调整时发生冲突
        if (m_refreshTimer && m_refreshTimer->isActive())
        {
            m_refreshTimer->stop();
            // 延迟重启定时器
            QTimer::singleShot(1000, this, [this]()
                               {
                if (m_refreshTimer) {
                    m_refreshTimer->start();
                } });
        }
    }
}